<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stroop Experiment</title>
    <link href="https://unpkg.com/jspsych@7.3.4/css/jspsych.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="jspsych-target"></div>

    <script src="https://unpkg.com/jspsych@7.3.4"></script>
    <script src="https://unpkg.com/@jspsych/plugin-html-keyboard-response@1.1.3"></script>
</body>
<style>
    /* 页面布局 */
    body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        font-family: Arial, sans-serif;
    }

    #jspsych-target {
        text-align: center;
    }

    .form-container {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .form-container input {
        margin: 10px;
        padding: 5px;
        font-size: 16px;
    }
</style>
<script>
    // 初始化 jsPsych
    const jsPsych = initJsPsych({
        on_finish: function() {
            jsPsych.data.displayData();
        }
    });

    // 收集被试信息
    const participantInfo = {
        type: jsPsychHtmlKeyboardResponse,
        stimulus: `
            <div class="form-container">
                <h3>请输入您的信息</h3>
                <form id="participant-form">
                    <label for="id">被试编号:</label>
                    <input type="text" id="id" name="id" required>
                    <label for="name">姓名:</label>
                    <input type="text" id="name" name="name" required>
                    <input type="submit" value="提交">
                </form>
            </div>
        `,
        choices: "NO_KEYS",
        on_load: function() {
            document.getElementById('participant-form').addEventListener('submit', function(event) {
                event.preventDefault();
                const id = document.getElementById('id').value;
                const name = document.getElementById('name').value;
                jsPsych.data.addDataToLastTrial({ participant_id: id, participant_name: name });
                jsPsych.finishTrial();
            });
        }
    };

    // 定义stroop实验的颜色和词语
    const colors = ['red', 'green', 'blue', 'yellow'];
    const words = ['红', '绿', '蓝', '黄','董'];

    // Generate trials
    function generateTrials(numTrials) {
        let trials = [];
        for (let i = 0; i < numTrials; i++) {
            let word = words[Math.floor(Math.random() * words.length)];
            let color = colors[Math.floor(Math.random() * colors.length)];
            trials.push({
                stimulus: `<p style="font-size:48px; color:${color};">${word}</p>`,
                correct_response: color[0]
            });
        }
        return trials;
    }

    // 指导语
    const instruction = {
        type: jsPsychHtmlKeyboardResponse,
        stimulus: "欢迎来到Stroop实验，请按照看到的字体颜色进行按键反应，红色请按r，绿色按g，蓝色按b，黄色按y。10秒后或按空格键开始练习试次",
        choices: [" "],
        trial_duration: 10000,
        response_end_trial: true
    };

    // 练习试次
    function createPracticeTrial(trial) {
        return {
            type: jsPsychHtmlKeyboardResponse,
            stimulus: trial.stimulus,
            choices: ['r', 'g', 'b', 'y'],
            on_finish: function(data) {
                data.correct = data.response === trial.correct_response[0];
            }
        };
    }

    // 练习试次反馈
    const practiceFeedback = {
        type: jsPsychHtmlKeyboardResponse,
        stimulus: function() {
            const lastData = jsPsych.data.get().last(1).values()[0];
            if (lastData.correct) {
                return "<p>正确！按空格键继续。</p>";
            } else {
                return "<p>错误。按空格键继续。</p>";
            }
        },
        choices: [" "],
        trial_duration: 1000
    };

    // 是否重复练习
    const practiceFeedbackSummary = {
        type: jsPsychHtmlKeyboardResponse,
        stimulus: function() {
            const practiceData = jsPsych.data.get().filter({trial_type: 'html-keyboard-response'}).last(5);
            const correctCount = practiceData.filter({correct: true}).count();
            const totalCount = practiceData.count();
            return `<p>练习结束！</p>
                    <p>按空格键继续到正式实验，或者按r键重新练习。</p>`;
        },
        choices: [" ", "r"],
        on_finish: function(data) {
            jsPsych.data.addDataToLastTrial({ response: data.response });
        }
    };

    // 设置注视点属性
    const fixationCross = {
        type: jsPsychHtmlKeyboardResponse,
        stimulus: '<p style="font-size:48px;">+</p>',
        choices: "NO_KEYS",
        trial_duration: 500
    };

    // 试次注视点
    function createStroopTrial(trial) {
        return {
            type: jsPsychHtmlKeyboardResponse,
            stimulus: trial.stimulus,
            choices: ['r', 'g', 'b', 'y'],
            on_finish: function(data) {
                data.correct = data.response === trial.correct_response[0];
            }
        };
    }

    const stroopTrials = generateTrials(20).flatMap(trial => [
        fixationCross,
        createStroopTrial(trial),
        fixationCross
    ]);

    // 练习试次注视点
    function createPracticeTrialWithFixation(trial) {
        return [
            fixationCross,
            createPracticeTrial(trial),
            practiceFeedback,
            fixationCross
        ];
    }

    function addPracticeTimeline() {
        const practiceTimeline = [];
        const practiceTrials = generateTrials(5);
        
        practiceTrials.forEach(trial => {
            practiceTimeline.push(...createPracticeTrialWithFixation(trial));
        });

        practiceTimeline.push(practiceFeedbackSummary);

        return practiceTimeline;
    }

    function runPractice() {
        return {
            timeline: addPracticeTimeline(),
            loop_function: function(data) {
                const lastResponse = jsPsych.data.get().last(1).values()[0].response;
                if (lastResponse === 'r') {
                    return true;
                } else {
                    practiceComplete = true;
                    return false;
                }
            }
        };
    }

    // 创建时间线
    let timeline = [];  
    timeline.push(participantInfo);  // Add participant information collection to timeline
    timeline.push(instruction);  

    let practiceComplete = false;

    timeline.push(runPractice());

    timeline.push(...stroopTrials);  
    timeline.push({
        type: jsPsychHtmlKeyboardResponse,
        stimulus: "感谢您参与本次实验，10秒后或按空格键结束实验",
        choices: [" "],
        trial_duration: 10000,
        response_end_trial: true
    });  
    
    // Run the experiment
    jsPsych.run(timeline);
</script>
